﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Interop;

using AtletIS.Shared.Entities;
using AtletIS.Shared.Data.aDbDataSetTableAdapters;
using AtletIS.Shared.Helpers;

namespace AtletIS.Shared.WpfControls
{
    public partial class ChipViewer : UserControl
    {
        private DisciplineListEntity discipline;

        private DisciplineListTableAdapter taDisciplineList = new DisciplineListTableAdapter();
        private CheckPointsTableAdapter taCheckPoints = new CheckPointsTableAdapter();
        private ChipDataTableAdapter taChipData = new ChipDataTableAdapter();

        private System.Windows.Forms.Timer tmrRefresh;
        private DataTable dtChipData;
        private string sStartTime = string.Empty;
        private int checkPointId;

        // Constructor
        public ChipViewer(DisciplineListEntity discipline)
        {
            InitializeComponent();
            this.discipline = discipline;

            // Title
            cbTitle.title1 = discipline.Name;
            cbTitle.title2 = "Chip Viewer";
        }

        // Form Load
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            // Check-pointy
            DataTable dtCheckPoints = DatabaseHelper.GetCheckPointsByDisciplineListIdActive(discipline.ID, false); 
            // taCheckPoints.GetActiveByDisciplineListId(discipline.ID);
            this.dgCheckPoints.ItemsSource = dtCheckPoints.AsDataView();
            try
            {
                if (dgCheckPoints.Items[0] != null)
                {
                    DataRowView drv = (DataRowView)dgCheckPoints.Items[0];
                    this.checkPointId = Convert.ToInt32(drv["ID"]);
                }
            }
            catch 
            { 
                
            }

            // Timer
            this.tmrRefresh = new System.Windows.Forms.Timer();
            this.tmrRefresh.Interval = 1000;
            this.tmrRefresh.Tick += new System.EventHandler(this.tmrRefresh_Tick);
            this.tmrRefresh.Enabled = true;
            this.RefreshData();
        }

        // Timer Tick
        private void tmrRefresh_Tick(object sender, EventArgs e)
        {
            this.RefreshData();
        }

        // Refresh data
        private void RefreshData()
        {
            lbTopThree.Items.Clear();
            lbNext.Items.Clear();

            if (dgCheckPoints.Items.Count == 0)
                return;

            this.discipline = Helpers.DisciplineListHelper.ConvertToEntity(DatabaseHelper.GetDisciplineListById(discipline.ID).Rows[0]); // taDisciplineList.GetById(discipline.ID).Rows[0]);
            
            try
            {
                dtChipData = DatabaseHelper.GetChipDataByCheckPointId(this.checkPointId); // taChipData.GetByCheckPointId(this.checkPointId);
                if (dtChipData.Rows.Count <= 11)
                {
                    // Top 3
                    for (int i = 0; i < 1; i++)
                    {
                        if (i < dtChipData.Rows.Count)
                        {
                            lbTopThree.Items.Add(GetChipViewerBox(dtChipData.Rows[i], i + 1));
                        }
                    }

                    // Next
                    for (int i = 1; i < 11; i++)
                    {
                        if (i < dtChipData.Rows.Count)
                        {
                            lbNext.Items.Add(GetChipViewerBox(dtChipData.Rows[i], i + 1));
                        }
                    }
                }
                else
                {
                    // Top 3
                    for (int i = 0; i < 1; i++)
                    {
                        lbTopThree.Items.Add(GetChipViewerBox(dtChipData.Rows[i], i + 1));
                    }

                    // Next
                    for (int i = dtChipData.Rows.Count - 10; i < dtChipData.Rows.Count; i++)
                    {
                        lbNext.Items.Add(GetChipViewerBox(dtChipData.Rows[i], i + 1));
                    }
                }
            }
            catch (Exception ex)
            {
                tmrRefresh.Enabled = false;
                MessageBox.Show("Nastala chyba pri generovaní výsledkov!" + Environment.NewLine + ex.Message, "Chip Viewer", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        // Get ResultBox
        private ChipViewerBox GetChipViewerBox(DataRow dr, int nOrder)
        {
            // Get and round time
            DateTime chipDateTime = Convert.ToDateTime(dr["ChipDateTime"]);
            chipDateTime = RoundingHelper.RoundUpDateTime(chipDateTime, discipline.ResultCode);
            string sResult = PrintHelper.PrintResult2(chipDateTime, discipline.ResultCode);

            // Penalties
            string[] aExtTexts;
            DataTable dtExtTexts = DatabaseHelper.GetExtTextsByPerformanceIdActive(Convert.ToInt32(dr["PerformanceId"])); 
            if (dtExtTexts.Rows.Count > 0)
            {
                aExtTexts = new string[dtExtTexts.Rows.Count];
                for (int i = 0; i < dtExtTexts.Rows.Count; i++)
                {
                    aExtTexts[i] = dtExtTexts.Rows[i]["Text1"].ToString();
                }
            }
            else
                aExtTexts = null;

            ChipViewerBox grb = new ChipViewerBox(nOrder,
                Convert.ToInt32(dr["StartNumber"]),
                dr["CountryId"].ToString(),
                dr["Surname"].ToString().ToUpper() + " " + dr["FirstName"].ToString(),
                sResult,
                aExtTexts);

            return grb;
        }

        // Zmena Check-pointu
        private void dgCheckPoints_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                if (dgCheckPoints.CurrentItem != null)
                {
                    DataRowView drv = (DataRowView)dgCheckPoints.CurrentItem;
                    this.checkPointId = Convert.ToInt32(drv["ID"]);
                }
            }
            catch { }
        }

        // Close
        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            HwndSource source = (HwndSource)PresentationSource.FromVisual(sender as Button);
            System.Windows.Forms.Control ctl = System.Windows.Forms.Control.FromChildHandle(source.Handle);
            ctl.FindForm().Close();  
        }





    }
}
